/**
 * pseudocode
  1. 请求mysql数据库中存储的实时车流量以及路段坐标数据
  2. 将坐标解析成二维数组的格式
  3. 分级设色
  4. 设置属性
 * @ {object} currentRoadsSource 存放实时路况的数据源
 * @return 如果当前实时路况图层存在, 再次触发该函数时清空该数据源
 */
let id
function showCurrentRoads() {
	//判断当前实时路况图层是否有要素数据
	//console.log(currentRoadsSource.getFeatures())
	// if (currentRoadsSource.getFeatures()[0]) {
	//   currentRoadsSource.clear()
	//   window.clearInterval(id)
	//   return
	// }
	$.ajax({
		url: BaseURL + '/all/gg_traffic',
		type: 'GET',
		success: function (res) {
			//获取到后台返回的数据
			if (res.code == 1) {
				//得到线坐标数据 "114.33209,30.476066;114.330889,30.469543"
				res.result.roads.forEach((element) => {
					const {
						traffic_path,
						traffic_time,
						traffic_road,
						traffic_vehicleflow,
					} = element

					//线: 一维数组 ['114.33209,30.476066','114.330889,30.469543']
					//console.log(element.traffic_path.split(';'))
					//线: 二维数组 [[114.33209,30.476066],[114.330889,30.469543]]
					const line = traffic_path.split(';').map((item) => {
						return item.split(',')
					})

					//创建一个线要素(设置几何以及属性)
					const currentRoadsFeature = new ol.Feature({
						geometry: new ol.geom.LineString(line),
						traffic_time,
						traffic_road,
						traffic_vehicleflow,
					})

					//设置线要素的样式
					let color
					if (traffic_vehicleflow < 300) {
						color = 'rgb(34,139,34)'
					} else if (traffic_vehicleflow < 500) {
						color = 'rgb(255,127,36)'
					} else {
						color = 'rgb(178,34,34)'
					}
					currentRoadsFeature.setStyle(
						new ol.style.Style({
							//边线颜色
							stroke: new ol.style.Stroke({
								color: color,
								lineJoin: 'square',
								//lineJoin: "miter",//round或miter
								width: 6,
							}),
						})
					)
					//将线要素添加到数据源
					currentRoadsSource.addFeature(currentRoadsFeature)
				})
			}
		},
	})
}
function handleClickCurrentRoads() {
	map.on('click', addPopup)
	//判断当前实时路况图层是否有要素数据
	//console.log(currentRoadsSource.getFeatures())
	if (currentRoadsSource.getFeatures()[0]) {
		currentRoadsSource.clear()
		window.clearInterval(id)
		return
	}
	showCurrentRoads()
	id = window.setInterval(showCurrentRoads, 1000)
}
